package com.jm.controller;

import com.jm.domain.ResponseResult;
import com.jm.domain.entity.LoginUser;
import com.jm.domain.entity.Menu;
import com.jm.domain.entity.User;
import com.jm.domain.vo.AdminUserInfoVo;
import com.jm.domain.vo.RoutersVo;
import com.jm.domain.vo.UserInfo;
import com.jm.enums.AppHttpCodeEnum;
import com.jm.exception.SystemException;
import com.jm.service.LoginService;
import com.jm.service.MenuService;
import com.jm.service.RoleService;
import com.jm.utils.BeanCopyUtils;
import com.jm.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserLoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user) {
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

    /**
     * 查询登录用户的权限、角色、用户详细
     * @return
     */
    @GetMapping("/getInfo")
    public ResponseResult getInfo() {
        //从SCH中获取用户id
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //查询用户的权限信息
        List<String> perms=menuService.selectPermsByUserId(loginUser.getUser().getId());
        //查看用户的角色
        List<String> roles=roleService.selectRolesByUserId(loginUser.getUser().getId());
        //查看用户的详细信息
        User user = loginUser.getUser();
        UserInfo userInfo = BeanCopyUtils.copyBean(user, UserInfo.class);

        //封装返回
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roles,userInfo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        //从SCH中获取用户id
        Long userId = SecurityUtils.getUserId();
        //查询menu 树形显示
        List<Menu> menus=menuService.selectRoutersMenuTreeByUserId(userId);

        //封装返回
        RoutersVo routersVo = new RoutersVo(menus);
        return ResponseResult.okResult(routersVo);
    }


}
